package com.code.leetcode.before50;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author codeDorado
 * @version 1.0
 * @date 2020/7/24 15:21
 *
 * 滑动窗口
 */
public class The76 {
    Map<Character, Integer> ori = new HashMap<>();
    Map<Character, Integer> cnt = new HashMap<>();

    public String minWindow(String s, String t) {
        int tlen = t.length();
        for (int i = 0; i < tlen; i++) {
            char c = t.charAt(i);
            ori.put(c, ori.getOrDefault(c, 0) + 1);
        }
        int slen = s.length();
        int l = 0, r = -1;
        int len = Integer.MAX_VALUE, ansl = -1, antr = -1;
        while (r < slen) {
            r++;
            if (r < slen && ori.containsKey(s.charAt(r))) {
                cnt.put(s.charAt(r), cnt.getOrDefault(s.charAt(r), 0) + 1);
            }

            while (check() && l <= r) {
                if (r - l + 1 < len) {
                    len = r - l + 1;
                    ansl = l;
                    antr = l + len;
                }
                if (ori.containsKey(s.charAt(l))) {
                    cnt.put(s.charAt(l), cnt.getOrDefault(s.charAt(l), 0) - 1);
                }
                l++;
            }
        }
        return ansl == -1 ? "" : s.substring(ansl, antr);

    }

    public boolean check() {
        Iterator iterator = ori.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            Character key = (Character) entry.getKey();
            Integer value = (Integer) entry.getValue();
            if (cnt.getOrDefault(key, 0) < value) {
                return false;
            }
        }
        return true;
    }
}
